/* Copyright (c) 2004-2024 Peigen.info. All rights reserved. */

package info.peigen.hotpot.component.gateway.socket.protocol;

import lombok.extern.slf4j.Slf4j;
import org.smartboot.socket.Protocol;
import org.smartboot.socket.transport.AioSession;

import java.nio.ByteBuffer;

/**
 * <b>(AbstractSocketProtocol)</b>
 *
 * @author Peigen
 * @version 1.0.0
 * @since 2022/8/11
 */
@Slf4j
public abstract class AbstractSocketProtocol<T> implements Protocol<T> {

    /**
     * 解码
     *
     * @param bitStr  String
     * @param session AioSession
     *
     * @return T
     */
    protected abstract T decode(String bitStr, AioSession session);

    @Override
    public final T decode(ByteBuffer readBuffer, AioSession session) {
        String hexStr = toHex(readBuffer);
        log.info("收到原始报文：" + hexStr);
        return decode(hexStr, session);
    }

    public static String toHex(ByteBuffer bb) {
        StringBuilder sb = new StringBuilder("[ ");
        while (bb.hasRemaining()) {
            sb.append(String.format("%02X ", bb.get()));
        }//from  w w  w.  j  a va  2  s .  c  o  m
        sb.append("]");
        return sb.toString();
    }
}